package com.by.service.impl;

import com.by.bean.Order;
import com.by.common.crud.BaseServiceImpl;
import com.by.common.utils.Assert;
import com.by.mapper.GoodsMapper;
import com.by.mapper.OrderDetailMapper;
import com.by.mapper.OrderMapper;
import com.by.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class OrderServiceImpl extends BaseServiceImpl<Order, OrderMapper> implements OrderService {

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    GoodsMapper goodsMapper;

    /**
     *
     * @param entity
     * @return 0失败 >0 成功 且值代表订单id
     */
    @Transactional
    @Override
    public int save(Order entity) {
        //生成商户平台订单
        //自动生成订单编号
        entity.setOrderNum("dd202503001");
        //订单收货人信息（1.前端传递所有信息 2.前端传递收获地址id 3.如果没传 默认收货地址）
        //假如传递收货地址id 判断: 如果没有传递 根据用户id查询默认地址 如果传了 根据收货地址id查询
        //判断如果entity中addressId为0 则根据用户id查询默认收货地址

        //保存订单
        int rs = baseMapper.save(entity);
        Assert.isZero(rs, "保存订单失败");

        //保存订单明细
        if (null!=entity.getOrderDetails() && entity.getOrderDetails().size()>0){
            rs=orderDetailMapper.batchSave(entity.getId(),entity.getOrderDetails());
            Assert.isZero(rs,"保存订单明细失败");

            //模拟扣减库存
            entity.getOrderDetails().forEach(el->{
                int tmp = goodsMapper.updateStock(el.getGoodsId(),el.getNum());
                Assert.isZero(tmp,"扣减商品["+el.getGoodsId()+"]的库存"+el.getNum()+"失败");
            });
        }



        return entity.getId();
    }
}
